package com.onegene.pdf.exception;

import com.onegene.pdf.component.entity.Result;
import com.onegene.pdf.util.DataException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author laoliangliang
 * @date 2019/12/03 10:22
 */
@ControllerAdvice
@Slf4j
public class SystemExceptionHandler {


    @ExceptionHandler(value = {HttpMessageNotWritableException.class})
    @ResponseBody
    public void dataExceptionHandler(HttpServletRequest request, HttpMessageNotWritableException e) {
        // CODEX 2020/7/8: 不需要显示该错误
        if ("No converter for [class com.onegene.pdf.component.entity.Result] with preset Content-Type 'application/octet-stream'".equals(e.getMessage())) {
            return;
        }
        throw e;
    }

    @ExceptionHandler(value = {DataException.class})
    @ResponseBody
    public Result dataExceptionHandler(HttpServletRequest request, Exception e) {
        String msg = e.getMessage();
        return getExceptionResult(e, 50000, msg, false);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result commonExceptionHandler(HttpServletRequest request, Exception e) {
        return getExceptionResult(e, 50000, e.getMessage(), true);
    }

    private Result getExceptionResult(Exception e, int statusCode, String msg, boolean ignoreAlert) {
        e.printStackTrace();
        String exceptionName = ClassUtils.getShortName(e.getClass());
        StackTraceElement[] stackTrace = e.getStackTrace();
        StringBuilder sb = new StringBuilder();
        for (StackTraceElement stackTraceElement : stackTrace) {
            sb.append(stackTraceElement.toString()).append("\n");
        }
        String message = e.getMessage();
        if (ignoreAlert) {
            log.error("ExceptionName ==> {}，message:{},detail:{}", exceptionName, message, sb.toString());
        }
        return Result.failure(statusCode, msg);
    }
}
